<template>
	<view style="font-size: 13px;">
		<cu-custom bgColor="bg-gradual-blue" :isBack="true"><block slot="backText">返回</block><block slot="content">{{okr.id ? '编辑okr':'新增okr'}}</block></cu-custom>
		<view class="cu-form-group" >
			<!-- <view class="title cuIcon-add" style="color: blue;">添加对齐</view> -->
			<input placeholder="请输入okr名称" name="name" v-model="okr.name"></input>
		</view>
		
		<view class="cu-form-group" @tap="selectAlignment()">
			<view class="alignment-container">
				
				<!-- <view class="cuIcon-activityfill" style="size: 20px;" >对标关键结果</view> -->
				<div class="cuIcon-activityfill" style="font-size: 13px; display: block;">
					对标关键结果：
					<div class="alignment-row" v-if="showOkrAlignmentList && showOkrAlignmentList.length > 0" v-for="(a, index) in showOkrAlignmentList" :key="index">
						<view class="">
							{{ a.name? a.name: (a.targetName? a.targetName:a.okrName) }}{{ index < showOkrAlignmentList.length - 1 ? '，' : '' }}
						</view>
					</div>
				</div>
			</view>
		</view>
		
		<!-- 负责人 -->
		<view class="cu-form-group" :class="menuArrow ? 'arrow' : ''" @click="leaderSelect" style="display: flex; justify-content: space-between;">
		  <view class="content" style="display: flex; align-items: center;">
		    <text class="">负责人</text>
		  </view>
		  <view class="action" style="display: flex; align-items: center;">
		    <text class="text-grey text-sm">{{leader.name}}</text><text class="cuIcon-right"></text>
		  </view>
		</view>
		
		<view class="cu-form-group ">
			<view class="title">周期选择</view>
			<picker @change="PickerChange" :value="index" :range=cycleNames>
				<view class="picker">
					{{index>-1?cycleNames[index]:'周期'}}
				</view>
			</picker>
		</view>
		<view class="cu-form-group ">
		  <view class="title">类型</view>
		  <view class="button-containerType">
		    <button class="button-right" :class="{ 'selected-button': type === '0' }" @click="selectButton('0')">公司级</button>
		    <button class="button-right" :class="{ 'selected-button': type === '1' }" @click="selectButton('1')">个人级</button>
		  </view>
		</view>
		<view class="cu-form-group" :class="menuArrow ? 'arrow' : ''" @click="selectStaff" style="display: flex; justify-content: space-between;">
		  <view class="content" style="display: flex; align-items: center;">
		    <text class="">参与人</text>
		  </view>
		  <view class="action" style="display: flex; align-items: center;">
		    <view class="cu-avatar-group" v-for="item in ids" :key="item.id" style="padding: 0;">
		      <view class="cu-avatar round sm" :style="{ 'background-image': 'url(' + item.avatar + ')' }" style="margin-left: -10px;"></view>
		    </view>
		    <text class="text-grey text-sm">{{ ids.length }} 人</text>
		  </view>
		</view>
		<view class="cu-form-group" style="margin-top: 7px;" v-for="(item, index) in krList" :key="index">
			<view class="title" style="color: blue;">{{ calculateName(item, index) }}</view>
			<textarea v-model="item.name" rows="4" placeholder="请输入KR名称"></textarea>
			<view class="cuIcon-delete" @click="delKR(index)"></view>
		</view>
		<button class=" cuIcon-add" style="width: 95%;height: 70rpx;background-color: white;margin-top: 7px;" @click="addView">添加关键结果</button>
		<view class="cu-form-group" style="margin-top: 7px;">
			<button style="width: 45%;background-color: skyblue;" @click="addOkr"> 提交</button>
			<button style="width: 45%;" @click="cancleAdd" v-if="!okr.id"> 取消</button>
			<button style="width: 45%;" @click="delOkr" v-if="okr.id"> 删除</button>
		</view>
	
	<!-- 弹出框选择对标的OKR -->
	<popup-layer ref="popupRef" :direction="'top'" > <!-- 设置弹出层的高度 -->
		<view style="text-align: center; font-size: 20px;" class="margin-top margin-bottom" @tap="chengeCycle">{{ alignmentCycle.name }}(一个OKR只能选中一项)</view>
	  <!-- 为弹出层内容容器添加滚动条样式 -->
	  <view class="content bg-gray" style="overflow-y: auto;height: 450px;padding: unset;font-size: 11px;"> <!-- 添加样式以启用垂直滚动 -->
					<view class="custom-view" style="margin: 10px;" v-for="(item, index) in allOkrList" :key="index">
						
						<view  style="border-bottom: 1px solid;">
							<view class="" style="display: flex; justify-content: space-between; align-items: center;background-color: white;">
							  <view class="title bg-white" style="font-size: 20px; padding: 10px;">
								{{ item.name }}
							  </view>
							</view>
							<div class="item-container bg-white" style=" display: flex; block;padding: 10px;">
							  <div style="display: flex; align-items: center;">
								<div>
								  负责人：{{item.leaderName}}，进度：
								</div>
								<div style="flex: 1;">
								  <liu-progressbar :textInside="false" :progress="item.progress" color="#333333" :height="'10rpx'" style="width: 300rpx;"/>
								</div>
							  </div>
							</div>
						</view>
						<view class="bg-white" style=" block;padding: 10px;" v-for="(kr, index2) in item.subOkrList" :key="index2" >
							<view :class="{ selected: kr.selected }" @click="selectKR(kr,index,index2)" style="display: flex; justify-content: space-between; align-items: center;background-color: white;">
								<view class="title" style="display: block;">
									{{ kr.content }}：{{ kr.name }}
								</view>
								<div :class="{ 'circle': true, 'selected': kr.selected }">
								  <div class="check-mark" v-if="kr.selected">&#10003;</div>
								</div>
							</view>
						</view>
					</view> 
	  </view>
				<view class="button-container">
					<button class="" style="font-size: 15px;width: 200px;flex: unset;height: 40px;" @click="cancleSelcct">取消</button>
					<button class="confirm-button" style="font-size: 15px;width: 200px;flex: unset;height: 40px;" @click="comsumSelect">确定</button>
				</view>
	</popup-layer>
	
	<popup-layer ref="cyclePopupRef" :direction="'top'"> <!-- 设置弹出层的高度 -->
	<view style="text-align: center; font-size: 20px;" class="margin-top margin-bottom">周期选择</view>
	  <!-- 为弹出层内容容器添加滚动条样式 -->
	  <view class="content bg-gray" style="overflow-y: auto;height: 350px;"> <!-- 添加样式以启用垂直滚动 -->
		<view class="" v-for="(item, index) in cycleList" :key="index">
		  <view class="cu-form-group margin-top" @click="selectCycle(item, index)">
		  	<div class="left-content">
		  	    <div class="info">
		  	        周期名：{{item.name}}
		  	    </div>
		  	    <div class="info">
		  	        周期时间：{{item.startTime}} ~ {{item.endTime}}
		  	    </div>
		  		<div class="info">
		  		    周期状态：
		  		    <span v-if="item.startTime > currentTime" style="color: blueviolet;">未开始</span>
		  		    <span v-else-if="item.endTime >= currentTime && item.startTime <= currentTime" style="color: green;">进行中</span>
		  		    <span v-else style="color: red;">已结束</span>
		  		</div>
		  	</div>
		  	
		  </view>
		</view>
	  </view>
	</popup-layer>
	
	
	</view>
</template>

<script>
	import iconfont from '../../font_4280116_f6izbgedf4m/iconfont.css';
	import MessageSender from '@/utils/sendMessage.js';
	import request from '../../common/request';
	import common from 'common/common.js';
	export default {
		data() {
			return {
				tip: '请选择对标关键结果',
				//kr
				kr:{},
				views: [], // 用于存储动态添加的 <view> 元素
				 krList: [
					 {
						 content:"KR1",
						 name: '',
					 }
				 ], // 用于存储包含 name 和 content 属性的对象
				// 参与人
				menuArrow: '',
				ids: [],
				// 类型选择框
				type: '1',
				index: -1, 
				cycleList: [],
				allOkrList: [],
				selectedList: [],
				cycle: {},
				okr: {},
				leader: {},
				staff: {},
				alignmentCycle: {},
				cycleId: '',
				showOkrAlignmentList:[],
				alignmentList:[],
				alignment:{},
			}
		},
		onLoad(options) {
			if(options.data){
				// 新增
				this.cycle = JSON.parse(decodeURIComponent(options.data));
				this.cycleId = this.cycle.id;
			}
			
			if(options.okr){
				// 回显
				this.okr = JSON.parse(decodeURIComponent(options.okr));
				this.cycleId = this.okr.cycleId;
				this.krList = this.okr.subOkrList;
				this.index = this.okr.type;
				this.selectButton(this.index);
				this.ids = this.okr.staffList;
				if(this.okr.okrLeader.id){
					this.leader = this.okr.okrLeader;
				}
				if(this.okr.alignmentList){
					this.showOkrAlignmentList = this.okr.alignmentList;
				}
		
			}
			this.getAllCycle();
			this.staff = uni.getStorageSync("staff");
		},
		onShow() {
		},
		computed: {
			
			// 添加对齐
			addAlignment(){
				// 去空
				this.selectedList = this.selectedList.filter(item => item !== undefined && item !== null && item !== '');
				var _this = this;
				request({
					url: common.api_base_url+'/alignment/addAlignmentForOkr/' + _this.okr.id,	
					data:{
						"alignmentList": _this.selectedList,
					},
					method: 'PUT',
					success: res => {
						_this.selectedList = [];
						if(_this.showLeaderOkr == 0){
							_this.getOkrByStaffId();
						} else if(_this.showLeaderOkr == 1){
							_this.findOkrByLeader();
						}
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			
			// 把cycleList转换为名字，方便选中
			cycleNames() {
			  return this.cycleList.map(item => item.name);
			},
			currentTime() {
				const currentDate = new Date();
				return this.formatDate(currentDate); // 获取当前时间
			}
		},
		created() {
		    // 在组件创建时添加 popstate 事件监听器
		    window.addEventListener('popstate', this.handlePopstate);
		  },
		  destroyed() {
		    // 在组件销毁时移除 popstate 事件监听器，以防止内存泄漏
		    window.removeEventListener('popstate', this.handlePopstate);
		  },
		methods: {
			// 监听事件
			handlePopstate(event) {
				// 在这里执行与从上一个页面返回到本页面相关的操作
				const pages = getCurrentPages();
				const currentPage = pages[pages.length - 1];
				// 监听返回上个页面 pages/okrs/addOkr
				if (currentPage.route === 'pages/okrs/addOkr') {
					var ids = uni.getStorageSync("ids");
					this.ids = ids;
					var leader = uni.getStorageSync("leader");
					if(leader.id){
						this.leader = leader;
					}
				}
		    },
			// 点击开启周期选择弹框
			chengeCycle(){
				
				this.$refs.cyclePopupRef.show(); // 或者 boolShow = rue
			},
			// 选择周期
			selectCycle(cycle, index) {
				// 获取当前周期id
				this.alignmentCycle = this.cycleList[index]
				this.allOkrList = this.allOkrGroup[cycle.id]
				this.$refs.cyclePopupRef.close();// 或者 boolShow = false
			},
			// 点击确定
			comsumSelect(){
				this.$refs.popupRef.close();
				const copiedArray = JSON.parse(JSON.stringify(this.selectedList));
				this.showOkrAlignmentList = copiedArray.filter(item => item !== null);
				this.alignmentList = this.selectedList;
				// this.addAlignment();
			},
			// 点击取消
			cancleSelcct(){
				this.$refs.popupRef.close();
			},
			// 选中对标kr
			selectKR(okr) {
				// 当前okr对象
				if(okr.selected){
					// 选中了的，再点击，取消
					if(okr.parentId){
						// 说明是分任务
						this.selectedList[okr.parentId].selected = false;
						this.selectedList[okr.parentId] = null;
					} else {
						// 是okr主任务
						this.selectedList[okr.id].selected = false;
						this.selectedList[okr.id] = null;
					}
				} else{
					// 判断当前list里面有没有okr
					if(this.selectedList[okr.id] || this.selectedList[okr.parentId]){
						// 有，说明是切换
						okr.selected = true;
						if(okr.parentId){
							// 说明是分任务
							this.selectedList[okr.parentId].selected = false;
							this.selectedList[okr.parentId] = okr;
						} else {
							// 是okr主任务
							this.selectedList[okr.id].selected = false;
							this.selectedList[okr.id] = okr;
						}
					} else{
						// 无
						okr.selected = true;
						if(okr.parentId){
							// 说明是分任务
							this.selectedList[okr.parentId] = okr;
						} else {
							// 是okr主任务
							this.selectedList[okr.id] = okr;
						}
					}
				}
			},
			// 计算总进度
			calculateTotalProgress(krList) {
			      if (krList.length === 0) {
			        return 0;
			      }
			   return Number(krList.reduce((sum, item) => sum + parseFloat(item.progress), 0) / krList.length);
			},
			// 回显
			showBackAlignment(){
				// 做回显
				if(this.alignmentList){
					for (const alignment of this.alignmentList) {
						for (const key in this.allOkrGroup) {
						// 	// 遍历一个周期
							if(alignment.cycleId == key){
								// 当前周期下所有数据
								var okrList = this.allOkrGroup[key]
								for (const okr of okrList) {
									
									if (alignment.parentId) {
										
										// 如果存在，说明是子任务
										for (const kr of okr.subOkrList) {
											if (alignment.targetId === kr.id) {
												// 判断是哪一个子任务
												kr.selected = true;
												// 设置回selectedKrList
												this.selectedList[kr.parentId] = kr;
											}
										}
									} else {
										if (alignment.targetId === okr.id) {
											  // 这里是okr
											  okr.selected = true;
											  // 设置回selectedOkrList
											  this.selectedList[okr.id] = okr;
										}
									}
								}
								
							}
						  
						}
					}
				}
			},
			// 选择okr的显示周期
			selectedCycle(cycle){
				this.cycle = cycle;
				this.okrList = this.okrMap[cycle.id];
				this.$refs.cycleSelectPopupRef.close();// 或者 boolShow = false
			},
			// 显示okr的周期选中
			selectShowCycle(){
				this.$refs.cycleSelectPopupRef.show();// 或者 boolShow = false
			},
			// 获取当前周期所有OKR，用来对齐
			getAllOkrGroupBycycleId(){
				var _this = this;
				request({
					url: common.api_base_url+'/okr/getAllOkrGroupBycycleId',
					data:{
					},
					method: 'GET',
					success: res => {
						_this.allOkrGroup = res.data;
						_this.allOkrList = _this.allOkrGroup[_this.alignmentCycle.id];
						// 说明是回显
						if(_this.alignmentList.length > 0){
							// 回显
							_this.showBackAlignment();
						}
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 点击开启KR选择弹框，添加对齐
			selectAlignment(){
				this.alignmentCycle = this.cycleList[0]
				if(this.okr.id){
					// 说明是回显
					if(this.okr.alignmentList){
						this.alignmentList = this.okr.alignmentList;
					}
						this.getAllOkrGroupBycycleId();
					
				} else{
					// 说明是新增
					if(this.selectedList.length > 0){
						// 说明是新增回显
						
					} else{
						// 说明是第一次点击
						this.getAllOkrGroupBycycleId();
					}
				}
				
				// 点击对齐按钮之后，展示的周期
				// this.cycleId  = this.cycle.id;
				
				// this.getAllOkrGroupBycycleId();
				
				this.$refs.popupRef.show(); // 或者 boolShow = rue
				
			},
			// 删除okr
			delOkr(){
				if(this.staff.id !== this.okr.creatStaffId){
					uni.showToast({
						title:"权限不足",
						icon:"error"
					})
					return;
				}
				// 存在对齐
				if(this.okr.alignmentList){
					uni.showToast({
						title:"请取消所有对齐目标后再删除",
						icon:"error",
						duration: 2500
					})
					return;
				}
				var _this = this;
				uni.showModal({
				    title: '删除任务',
				    content: '您确定要删除这条任务吗？',
				    success: function (res) {
				        if (res.confirm) {
							request({
								url: common.api_base_url+'/okr/' + _this.okr.id,
								data:{
								},
								method: 'DELETE',
								success: res => {
									uni.navigateBack({
									    delta: 1,
									});
								},
								fail: function(e) {
									uni.showToast({
										title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
										icon:"loading"
									})
								},
							});
						} else if (res.cancel) {
							res.cancel = true;
						}
				    }
				});
			},
			getKrName(item){
				var index = this.krList.findIndex(function(e) {
				    return e.id === item.id;
				});
				item.content = "KR" + (index + 1);
				return item.content;
			},
			// 取消
			cancleAdd(){
				uni.navigateBack({
				    delta: 1,
				});
			},
			// 获取负责人，回显
			getLeader(){
				var _this = this;
				request({
					url: common.api_base_url+'/staff/' + _this.okr.leader,
					data:{
					},
					method: 'GET',
					success: res => {
						if(res.data){
							_this.leader = res.data;
						}
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 选中负责人
			leaderSelect(){
				uni.navigateTo({
					url:'/pages/addTask/leaderStaff?leader='+ encodeURIComponent(JSON.stringify(this.leader)),
				})
			},
			// 点击提交
			addOkr(){
				this.okr.type = this.type;
				this.okr.cycleId = this.cycle.id;
				this.okr.staffList = this.ids;
				this.okr.subOkrList = this.krList;
				if(!this.leader.id){
					uni.showToast({
						title:"请选择负责人",
						icon:"error"
					})
					return;
				}
				if(this.ids.length == 0){
					uni.showToast({
						title:"至少一个人参与",
						icon:"error"
					})
					return;
				}
				// 负责人
				if(this.leader.id){
					this.okr.leader = this.leader.id;
				}
				// 创建人
				if(this.staff.id){
					this.okr.creatStaffId = this.staff.id;
				}
				this.selectedList = this.selectedList.filter(item => item !== undefined && item !== null && item !== '');
				// 对齐
				if(this.selectedList.length > 0){
					this.okr.alignmentForOkrList = this.selectedList;
				}
				this.okr.progress = this.calculateTotalProgress(this.krList);
				
				var _this = this;
				request({
					url: common.api_base_url+'/okr',
					data:{
						"okr": _this.okr,
					},
					method: 'PUT',
					success: res => {
						// 给任务成员发送消息
						if(_this.ids){
							// 去掉最后一个，不给自己发消息
							// _this.ids.pop();
							// 如果还有
							if(_this.ids.length > 0){
								_this.ids.push(_this.staff)
								var touserTmp = _this.ids.map(item => item.userId);
								var touser = touserTmp.join("|");
								// 说明是新增
								if(_this.okr.id == null){
									var descript = "<div class=\"gray\">%s</div> <div class=\"normal\">您有新的相关okr创建，请点击查看</div><div class=\"highlight\">周期："+_this.cycle.name+"任务负责人："+ _this.leader.name +"，okr名称："+ _this.okr.name +"</div>";
								} else{
									var descript = "<div class=\"gray\">%s</div> <div class=\"normal\">您有相关okr更改，请点击查看</div><div class=\"highlight\">任务负责人："+ _this.leader.name +"，okr名称："+ _this.okr.name +"</div>";
								}
								
								MessageSender.sendMessage(touser, descript)
								  .then(response => {
									console.log('Message sent successfully:', response);
									// 在这里可以处理发送成功的逻辑
								  })
								  .catch(error => {
									console.error('Error sending message:', error);
									// 在这里可以处理发送失败的逻辑
								  });
							}
						}
						uni.removeStorageSync("ids");
						uni.removeStorageSync("leader");
						uni.navigateBack({
						    delta: 1,
						});
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 删除KR元素
			delKR(index){
				this.krList.splice(index, 1);
			},
			calculateName(kr, index){
				kr.content = 'KR' + (index + 1);
				return kr.content;
			},
			// 添加KR元素
			addView() {
				// 添加新的KR
				this.krList = this.krList.filter(e=> e != undefined);
			  const newItem = {
				  content: `KR${this.krList.length + 1}`,
				  name: '',
				  progress: 0
				};
				this.krList.push(newItem);
			},
			// 选择参与人员
			selectStaff(){
				// 选中了之后，回显
				uni.navigateTo({
					url:'/pages/addTask/selectStaff?ids='+ encodeURIComponent(JSON.stringify(this.ids)),
				})
			},
			// 改变类型选择框底色
			selectButton(type) {
				if(type == 0 && this.staff.id != 8){
					uni.showToast({
						title:"权限不足",
						icon:"error"
					})
					return;
				}
			    this.type = type;
			},
			// 周期单选
			PickerChange(e) {
				this.index = e.detail.value;
				this.cycle = this.cycleList[this.index];
			},
			// 获取所有周期
			getAllCycle(){
				var _this = this;
				request({
					url: common.api_base_url+'/cycle',
					data:{
					},
					method: 'GET',
					success: res => {
						_this.cycleList = res.data;
						_this.index = _this.cycleList.findIndex(item => item.id === _this.cycleId);
						_this.cycle = _this.cycleList[_this.index];
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 时间转换格式方法
			formatDate(date) {
			  const year = date.getFullYear();
			  const month = String(date.getMonth() + 1).padStart(2, '0');
			  const day = String(date.getDate()).padStart(2, '0');
			  return `${year}-${month}-${day}`;
			},
		}
	}
</script>

<style>
/* 类型选中样式 */
.button-container {
	
  display: flex;
  justify-content: flex-end; /* 将按钮靠右对齐 */
}

.button-containerType {
  display: flex;
  justify-content: flex-end; /* 将按钮靠右对齐 */
}


.button-right {
  font-size: 9px;
  padding: 0px 10px;
  margin-left: 10px; /* 为按钮之间添加一些间距，可根据需要调整 */
}

.selected-button {
  background-color: blue; /* 设置选中按钮的背景颜色为蓝色 */
  color: white; /* 设置选中按钮的文字颜色为白色 */
}

	/* .selected {
	  border: 2px solid red; 
	} */
	.alignment-row {
	  display: inline-block;
	  margin-right: 10px; /* 可以添加一些右侧间距，根据需要调整 */
	}
	.alignment-container {
	  display: flex;
	  align-items: center; /* 垂直居中对齐 */
	}
	
	/* 设置确定按钮的背景颜色为蓝色 */
	.confirm-button {
	  background-color: blue;
	  color: white;
	}
	
	
	.circle {
	    width: 30px;
	    height: 30px;
	    border-radius: 50%;
	    background-color: #dcdcdc;
	    display: inline-flex;
	    align-items: center;
	    justify-content: center;
	    cursor: pointer;
	    margin-right: 10px;
	  }
	
	  .circle.selected {
	    background-color: #99cc99; /* Selected color */
	  }
	
	  .check-mark {
	    font-size: 24px;
	    color: #fff;
	  }
	
</style>
